package com.example.iorder.reservation;

import org.json.JSONException;
import org.json.JSONObject;

import com.example.domain.Restaurant;
import com.example.iorder.R;
import com.example.iorder.config.Config;
import com.example.iorder.restaurant.RestaurantDetails_GeneralInformation;
import com.example.iorder.util.HTTPClient;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

public class ViewRestaurantInfo extends Activity {
	private ProgressDialog progress;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.reservation_view_restaurant_info);
		
		// Show loading indicator
        progress = new ProgressDialog(this);
        startLoadingIndicator();
        
        Bundle reservationInfo = getIntent().getExtras();
        final int restId = reservationInfo.getInt(getResources().getString(R.string.key_restaurant_id));
        
        // Start another thread to search for restaurants
        new Thread() {
        	public void run() {
        		Message msg = new Message();
        		String path = "";
        		HTTPClient httpClient = null;
        		String searchResult = "";
        		int restaurantId = restId;
        		
        		try {
        			path = Config.URL_RESTAURANTS + restaurantId;
        			httpClient = new HTTPClient(getBaseContext());
        			searchResult = httpClient.sendGETRequest(Config.IORDER_SERVER, path);
        			
        			msg.getData().putString("searchResult", searchResult);
        			searchOutputHandler.sendMessage(msg);
        		} catch (Exception e) {
        			msg.getData().putString("exception", e.toString());
        		}
        	}
        }.start();
	}
	
	@SuppressLint("HandlerLeak")
	private Handler searchOutputHandler = new Handler() {
		public void handleMessage(Message msg) {
			String newData = msg.getData().getString("searchResult");
			JSONObject record = null;
			//ArrayList<Restaurant> list = new ArrayList<Restaurant>();
			progress.dismiss();
			
			try {
				JSONObject jsonObject = new JSONObject(newData);
				if (jsonObject.has("data") && jsonObject.has("msg") && jsonObject.has("status")) {
					// Connection to server was successful and data was received 
					if (jsonObject.get("status").toString().equals("200")) {
						record = jsonObject.getJSONObject("data");
						try {
							String restaurantIdString = record.optString("ID");
							String restaurantName = record.optString("Name");
							String restaurantAddress = record.optString("Address");
							String restaurantCity = record.optString("City");
							String restaurantPhoneNumber = record.optString("PhoneNumber");
							String restaurantWebSite = record.optString("Website");
							String restaurantDescription = record.optString("Description");
							String restaurantEmailAddress = record.optString("EmailAddress");
							int id = Integer.parseInt(restaurantIdString);
							
							//(int id, String name, String address, String city, String phoneNumber, String kitchen)
							Restaurant newRestaurant = new Restaurant(id, restaurantName, restaurantAddress, restaurantCity, restaurantPhoneNumber, restaurantWebSite, restaurantDescription, restaurantEmailAddress, "");
				
							TextView guiName = (TextView) findViewById(R.id.r_restaurant_name_data);
							TextView guiAddress = (TextView) findViewById(R.id.r_restaurant_address_data);
							TextView guiCity = (TextView) findViewById(R.id.r_restaurant_city_data);
							TextView guiPhoneNumber = (TextView) findViewById(R.id.r_restaurant_phonenumber_data);
							TextView guiWebSite = (TextView) findViewById(R.id.r_restaurant_website_data);
							TextView guiEmailAddress = (TextView) findViewById(R.id.r_restaurant_email_address_data); 
							TextView guiDescription = (TextView) findViewById(R.id.r_restaurant_description_data);

							guiName.setText(RestaurantDetails_GeneralInformation.validateString(restaurantName));
							guiAddress.setText(RestaurantDetails_GeneralInformation.validateString(restaurantAddress));
							guiCity.setText(RestaurantDetails_GeneralInformation.validateString(restaurantCity));
							guiPhoneNumber.setText(RestaurantDetails_GeneralInformation.validateString(restaurantPhoneNumber));
							guiWebSite.setText(RestaurantDetails_GeneralInformation.validateString(restaurantWebSite));
							guiEmailAddress.setText(RestaurantDetails_GeneralInformation.validateString(restaurantEmailAddress));
							guiDescription.setText(RestaurantDetails_GeneralInformation.validateString(restaurantDescription));
							stopLoadingIndicator();			
						} 
						catch (Exception e) {
						}						
					} else {
						stopLoadingIndicator();
						Log.e("Request failure", jsonObject.get("msg").toString());
					}
				}
				else {
					Toast.makeText(getBaseContext(), "Faulty backend server response!", Toast.LENGTH_SHORT).show();
					stopLoadingIndicator();
				}
			} 
			catch (JSONException jsnE) {
				String errorMessage = "JSON Error: " + jsnE.getMessage();
				if (newData.equals("Error: No network")) {
					errorMessage = getResources().getString(R.string.no_network_connection);
				}
				Toast.makeText(getBaseContext(), errorMessage, Toast.LENGTH_LONG).show();
				stopLoadingIndicator();
			} 
			catch (Exception e) {
				Toast.makeText(getBaseContext(), "Error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
				stopLoadingIndicator();
			}
		}
	};
	
	public static String validateString(String restData) {
		if(restData != null)
			return restData;
		else
			return restData;
	}
	
	private void startLoadingIndicator() {
		progress.setTitle(getResources().getString(R.string.loading_title));
        progress.setMessage(getResources().getString(R.string.loading_message));
        progress.show();
	}
	
	private void stopLoadingIndicator() {
		progress.dismiss();
	}

}
